//
//  PYTableViewPageViewModel.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/26.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import HandyJSON
import RxSwift
import Moya
import Alamofire


///  列表页基础类 - ViewModel
class PYTableViewPageViewModel: NSObject, VGTableViewPageProtocol {
    
    public var vg_pagerModel: SGPagerModel<SGPagerTestModel>?
    
    public var getDataClosure: ((Int) -> Void)?
    
    public var loadDataClosure: ((Bool) -> Void)?
    
    var emptyViewParams: (String, String, CGFloat, CGFloat)!
    
    public var vg_dataCount: Int = 0
    
    public var vg_isLoading: Bool = false
    
    public var vg_pageNo: Int = 1
    
    public var size: Int = 10
    
    public var isNeedCache:Bool = false
    
    public var dataSource: [NSRecordsModel] = [] {
        didSet {
            vg_dataCount = dataSource.count
        }
    }
    
    public var model: PYQModel?
    
    public var title: String = "列表页标题"
    
    public var tableView: UITableView!
    
    var type: SYApiManager!
    
    var dispose: DisposeBag!
    
    override init() {
        super.init()
//        getCacheData()
    }
    
    ///解档-取数据
    public func getLocalData(url: String,succeed: (() -> Void)?) {
        dataSource.removeAll()
        model = nil
        
//        let resData:Data? = UserDefaults.standard.value(forKey: url + SYUserInfo.strand.userId) as? Data
        let data = UserDefaults.standard.value(forKey: url + SYUserInfo.strand.userId)
        let model = data as! PYQModel
        
        self.vg_pagerModel = SGPagerModel<SGPagerTestModel>()//PYQPagerModel()
        self.vg_pagerModel?.total = model.data?.ipage?.total
        self.vg_pagerModel?.current = model.data?.ipage?.current
        self.vg_pagerModel?.size = model.data?.ipage?.size
        self.vg_pagerModel?.pages = model.data?.ipage?.pages
        
        var s: [NSRecordsModel]!
        if let d = model.data?.ipage?.records {
            s = d
        }
        if let s = s{
            self.dataSource = s
            self.model = model
            succeed?()
        }
        
    }
    
    // 获取缓存
    fileprivate func getCacheData() {
        
        guard isNeedCache else {
            return
        }
        self.getLocalData(url: type.path) {[weak self] in
            DispatchQueue.main.async {
                if let weakSelf = self {
                    weakSelf.tableView.reloadData()
                    weakSelf.tableView.vg_endTableViewRefresh()
                }
            }
        }
    }
    
    public func getList(type: SYApiManager, dispose: DisposeBag) {
        
        vg_isLoading = true
        self.type = type
        self.dispose = dispose
        
        self.baseListRequest(disposeBag: dispose, type: type)
    }
    
    fileprivate func refreshViews(_ success: Bool) {
        if success {
//            tableView.reloadData()
        }
        tableView.vg_endTableViewRefresh()
        self.vg_isLoading = false
    }
    
    // MARK: - VGTableViewPageProtocol
    func vg_tableViewGetList() {
        getDataClosure?(vg_pageNo)
    }
    
    func vg_tableViewGetEmptyPageTitleAndImgUrl() -> (String, String, CGFloat, CGFloat) {
        return self.emptyViewParams
    }
    
    func baseListRequest(disposeBag: DisposeBag, type: SYApiManager) {
        DispatchQueue.main.async {
            HUDUtil.showHud()
        }
        ApiManagerProvider.rx.request(type)
            .asObservable()
            .mapHandyJsonModel(type.path, PYQModel.self)
            .subscribe {[weak self] (event) in
                
                DispatchQueue.main.async {
                    HUDUtil.hideHud()
                }
                if let `self` = self {
                    
                    switch event {
                    case let .next(data):
                        
                        let model = data
                        self.handleData(url: type.path, data: model)
                        self.loadDataClosure?(true)
                        self.refreshViews(true)
                        
                        break
                    case let .error(error):
                        print(error)
                        self.loadDataClosure?(false)
                        self.refreshViews(false)
                        
                        break
                    default:
                        break
                    }
                }
        }.disposed(by: disposeBag)
        
    }
    
    func handleData(url: String, data: PYQModel?) {
        
        self.vg_pagerModel = SGPagerModel<SGPagerTestModel>()//PYQPagerModel()
        self.vg_pagerModel?.total = data?.data?.ipage?.total
        self.vg_pagerModel?.current = data?.data?.ipage?.current
        self.vg_pagerModel?.size = data?.data?.ipage?.size
        self.vg_pagerModel?.pages = data?.data?.ipage?.pages
        
        var s: [NSRecordsModel]!
        if let d = data?.data?.ipage?.records {
            s = d
        }
        if self.vg_pageNo == 1 {
            if let s = s {
                self.dataSource = s
                self.model = data
                //归档-第一页数据
//                UserDefaults.standard.setValue(data, forKey: url + SYUserInfo.strand.userId)
            }
        } else {
            self.dataSource += s
        }
    }
}

